package com.lock.reentrantLock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @PackageName:com.lock.reentrantLock
 * @ClassName:Test07
 * @Description: tryLock()调用方法获得锁，没有被其他线程占有则返回true表示锁定成功，如果被其他线程占用则返回false，不等待。
 * @Author: zhangxiaoyu
 * @date 2021/1/19 18:05
 */
public class Test07 {

    static class Ser{

        private ReentrantLock lock = new ReentrantLock();

        public void serviceMethod(){
            try {
                if (lock.tryLock()){
                    System.out.println(Thread.currentThread().getName()+"获得锁定");
                    Thread.sleep(3000);
                }else {
                    System.out.println(Thread.currentThread().getName()+"没有获得锁定");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                if(lock.isHeldByCurrentThread()){
                    lock.unlock();
                }
            }
        }
    }


    public static void main(String[] args) throws InterruptedException {
        Ser ser = new Ser();

        Runnable r = new Runnable() {
            @Override
            public void run() {
                ser.serviceMethod();
            }
        };

        Thread t1 = new Thread(r);
        t1.start();
        Thread.sleep(50);  //确保t1线程确定

        Thread t2 = new Thread(r);
        t2.start();
    }
}
